package br.com.consultsystems.interfaces.wrapper;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

public class BigDecimalTypeAdapter extends TypeAdapter<BigDecimal> {
	
	@Override
	public BigDecimal read(JsonReader reader) throws IOException {
		
		/*
		 * Original
		 * return new BigDecimal(reader.nextString());
		 */
		DecimalFormat df = new DecimalFormat("#,##0.00");
		Number number;
		try {
			number = df.parse(reader.nextString());
			return new BigDecimal(number.doubleValue()).setScale(2, RoundingMode.HALF_UP);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return BigDecimal.ZERO;
	}

	@Override
	public void write(JsonWriter writer, BigDecimal value) throws IOException {

		/*
		 * Original
		 * writer.value(value);
		 */
		DecimalFormat df = new DecimalFormat("#,##0.00");
		writer.value(df.format(value.doubleValue()));
	}
}
